package yi.Note.ui;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.*;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import yi.Note.R;
import yi.Note.data.provider.NoteContent;
import yi.Note.util.ImageHelper;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: b251
 * Date: 13-12-14
 * Time: 下午9:03
 * To change this template use File | Settings | File Templates.
 */
public class AttGallery extends Gallery implements LoaderManager.LoaderCallbacks<Cursor>,AdapterView.OnItemClickListener {
    private BaseAdapter mAdapter;
    private AttHandlerCallback mCallback;

    public AttGallery(Context context) {
        super(context);
    }

    public AttGallery(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AttGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public static interface AttHandlerCallback{
        public void onAddAttachment();
        public void onDelAttachment(NoteContent.Attachment a);
        public void onClickAttachment(NoteContent.Attachment a);
    }

//    public void load(Activity owner){
//        mAdapter = new AttAdapter(owner, null, false);
//        setAdapter(mAdapter);
//        owner.getLoaderManager().initLoader(1, null, this);
//        setOnItemClickListener(this);
//    }

    public void load(Activity owner, BaseAdapter adapter){
        mAdapter = adapter;
        setAdapter(mAdapter);
        setOnItemClickListener(this);
    }

    public EditCacheAdapter createEditAdatper( NoteContent.Attachment[] cache){
        return new EditCacheAdapter(cache);
    }

    public AttAdapter createListAdatper(Activity owner){
        return new AttAdapter(owner, null, false);
    }

    public void setHandlerCallback(AttHandlerCallback callback){
        mCallback = callback;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new AttLoader(getContext());
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if(mAdapter instanceof CursorAdapter){
            ((CursorAdapter)mAdapter).swapCursor(data);
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        ((CursorAdapter)mAdapter).swapCursor(null);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        NoteContent.Attachment att = (NoteContent.Attachment)view.getTag();
        if(att.mId == NoteContent.ID_ADD){
            Toast.makeText(getContext(), "add click!", Toast.LENGTH_SHORT).show();
            mCallback.onAddAttachment();
            return;
        }
        mCallback.onClickAttachment(att);
    }

    public View newItemView(ViewGroup parent){
        LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        return inflater.inflate(R.layout.att_item, null);
    }

    public void bindToView(NoteContent.Attachment att, View view){
        view.setTag(att);
        if(att.mAttUri != null){
            Bitmap bitmap = decodeUriAsBitmap(Uri.parse(att.mAttUri), att.mSize);
            ImageView iv = (ImageView)view.findViewById(R.id.att_pic);
            if(bitmap != null){
                iv.setImageDrawable(new BitmapDrawable(getResources(), bitmap));
            } else {
                iv.setImageResource(R.drawable.ic_none);
            }
        }
    }

    private Bitmap decodeUriAsBitmap(Uri uri, int size){
        try {
            return ImageHelper.decodeImageUri(getContext(), uri, size);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public class EditCacheAdapter extends BaseAdapter{
        private LayoutInflater mInflater;
        private LinkedList<NoteContent.Attachment> mContents;
        public EditCacheAdapter(NoteContent.Attachment[] atts){
            mInflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mContents = buildContent(atts);
        }

        public List<NoteContent.Attachment> getAtts(){
            return Collections.unmodifiableList(mContents);
        }

        public void addAtt(NoteContent.Attachment att){
            mContents.addFirst(att);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mContents.size();
        }

        @Override
        public Object getItem(int position) {
            if(position>=mContents.size()) return null;
            return mContents.get(position);
        }

        @Override
        public long getItemId(int position) {
            if(position>=mContents.size()) return NoteContent.ID_NONE;
            return mContents.get(position).mId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            NoteContent.Attachment att = (NoteContent.Attachment)getItem(position);
            View view = null;
            if(att.mId==NoteContent.ID_ADD) {
                view = mInflater.inflate(R.layout.att_item_add, null);
            } else {
                view = newItemView(parent);
            }
            bindToView(att, view);
            return view;
        }

        private LinkedList<NoteContent.Attachment> buildContent(NoteContent.Attachment[] atts){
            LinkedList<NoteContent.Attachment> content = new LinkedList<NoteContent.Attachment>();
            content.addAll(Arrays.asList(atts));
            NoteContent.Attachment a = new NoteContent.Attachment();
            a.mId = NoteContent.ID_ADD;
            a.mNoteId = NoteContent.ID_NONE;
            a.mBaseUri = null;
            content.add(a);
            return content;
        }
    }

    public class AttAdapter extends CursorAdapter{
        private LayoutInflater mInflater;
        public AttAdapter(Context context, Cursor c,  boolean autoRequery) {
            super(context, c, autoRequery);
            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public boolean areAllItemsEnabled() {
            return super.areAllItemsEnabled();
        }

        @Override
        public boolean isEnabled(int position) {
            return super.isEnabled(position);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            long id = cursor.getLong(cursor.getColumnIndex(NoteContent.Attachment._ID));
            if(id<0){
                return mInflater.inflate(R.layout.att_item_add, null);
            }
            return newItemView(parent);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            NoteContent.Attachment a = new NoteContent.Attachment();
            a.restore(cursor);
            bindToView(a, view);
        }
    }

    private static class AttLoader extends CursorLoader{
        private Context mContext;
        public AttLoader(Context context) {
            super(context, NoteContent.Attachment.CONTENT_URI, NoteContent.Attachment.SELECT_PROJECTIONS, null, null, null);
            mContext = context;
        }

        @Override
        public Cursor loadInBackground() {
            final Cursor cursor =  super.loadInBackground();
            final Cursor opCursor = createAttOpCursor();
            if(cursor==null || cursor.getCount()==0){
                return opCursor;
            }
            return new MergeCursor(new Cursor[]{cursor, opCursor});
        }
    }

    private static Cursor createAttOpCursor() {
        MatrixCursor cursor = new MatrixCursor(NoteContent.Attachment.SELECT_PROJECTIONS);
        MatrixCursor.RowBuilder row = cursor.newRow();
        row.add(NoteContent.ID_ADD);
        row.add(NoteContent.ID_NONE);
        row.add(null);
        row.add(null);
        row.add(0);
        return cursor;
    }
}
